<?php

namespace catchAdmin\stock\controller;

use catchAdmin\permissions\model\Roles;
use catchAdmin\stock\request\WarehouseConfigCreateRequest;
use catchAdmin\stock\service\WarehouseConfigService;
use catchAdmin\storehouse\model\Tray;
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\stock\model\WarehouseConfig as WarehouseConfigModel;
use catchAdmin\stock\model\Stock;
use think\Response;
use catcher\CatchAuth;
use think\facade\Db;

class WarehouseConfig extends CatchController
{
    
    protected $warehouseConfigModel;
    
    /**
     *
     * @time 2022/01/17 13:52
     * @param WarehouseConfigModel $warehouseConfigModel
     * @return mixed
     */
    public function __construct(WarehouseConfigModel $warehouseConfigModel)
    {
        $this->warehouseConfigModel = $warehouseConfigModel;
    }
    
    /**
     * 库位列表
     * @time 2019年12月11日
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::success($this->warehouseConfigModel->getList($user['tenant_id']));
    }

    public function att(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::success($this->warehouseConfigModel->getAtt($user['tenant_id']));
    }
    public function  getSon(CatchAuth $auth,Request $request)
    {
        $params = $request->post();
        $user = $auth->user();

        if(!array_key_exists('config_id',$params)){
            return CatchResponse::fail('没有选择库区');
        }

        //父ID
        $parent_id = Db::table('db_warehouse_config')->where('config_id',$params['config_id'])->value('id');

        $where=[];
        if(!empty($params['search'])){
            $search = $params['search'];
            $where[]=['name','like',"%$search%"];
        }
        $where[] = ['parent_id','=',$parent_id];
        $ids = $this->warehouseConfigModel->where($where)->column('id');

        if(array_key_exists('config_used_status',$params) && 'empty' == $params['config_used_status']){
            $datas = $this->warehouseConfigModel->getEmptyConfig($ids);
            return CatchResponse::success($datas);
        }elseif (array_key_exists('config_used_status',$params) && 'notEmpty' == $params['config_used_status']){
            $datas = $this->warehouseConfigModel->getNotEmptyConfig($ids);
            return CatchResponse::success($datas);
        }

        //返回所有
        return CatchResponse::success($this->warehouseConfigModel->getSon($user['tenant_id'],$params['config_id']));
    }
    /**
     * 库位添加
     * @time 2022/01/17 13:52
     * @param Request $request
     * @return Response
     */
    public function create(CatchAuth $auth,WarehouseConfigCreateRequest $request) : Response
    {
        $params = $request->filterEmptyField()->post();
        $user = $auth->user();
        if(!empty($params['parent_id'])){
            $p_level=Db::table('db_warehouse_config')->where('id',$params['parent_id'])->value('level');
            $params['level']=intval($p_level)+1;
        }

        $params['tenant_id'] = $user['tenant_id'];
        $params['config_id'] = date('YmdHis');
        return CatchResponse::success($this->warehouseConfigModel->storeBy($params));
    }

    public function batchCreate(CatchAuth $auth,Request $request){
        $data = $request->filterEmptyField()->post('list');
        $user = $auth->user();

        $warehouseConfigService = new WarehouseConfigService;

        $err_arr = [];
        foreach ($data as &$params){
            if(!empty($params['parent_id'])){
                $p_level=Db::table('db_warehouse_config')->where('id',$params['parent_id'])->value('level');
                $params['level']=intval($p_level)+1;
            }else{
                $params['parent_id'] = 0;
            }
            $params['tenant_id'] = $user['tenant_id'];
            $params['config_id'] = $warehouseConfigService->getUniqueConfidId();
            $params['creator_id'] = $user['id'];

            //判断名称是否存在
            $nameIsExist = $this->warehouseConfigModel->where([
                'tenant_id'=>$user['tenant_id'],
                'name'=>$params['name'],
                'parent_id'=>$params['parent_id']
            ])->value('id');

            if($nameIsExist){
                $err_arr[$params['_XID']] = ['errMsg'=>'名称已存在'];
                continue;
            }
            unset($params['_XID'],$params['isUpload'],$params['disabled'],$params['errMsg']);

            (new \catchAdmin\stock\model\WarehouseConfig())->insert($params);
        }

        return CatchResponse::success($err_arr);
    }

    /**
     *
     * @time 2022/01/17 13:52
     * @param $id
     * @return Response
     */
    public function read($id) : Response
    {
        return CatchResponse::success($this->warehouseConfigModel->findBy($id));
    }
    
    /**
     * 库位修改
     * @time 2022/01/17 13:52
     * @param $id
     * @param Request $request
     * @return Response
     */
    public function update(WarehouseConfigCreateRequest $request) : Response
    {
        $params = $request->filterEmptyField()->post();

        //处理被过滤的。
        if(!array_key_exists('isstatus',$params)){
            //说明禁用
            $params['isstatus'] = 0;
        }

        $id = $params['id'];

        $ids = explode(',',$this->warehouseConfigModel->get_all_child_cate($id));
        $ids[] = $id;
        Db::startTrans();
        try {
            //更新所有下级的一个数据状态，禁用
            Db::table('db_warehouse_config')->where('id','in',$ids)->data(['isstatus'=>$params['isstatus']])->update();

            $res =  $this->warehouseConfigModel->updateBy($id,$params);
            Db::commit();
            return CatchResponse::success($res);
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('添加失败');
        }
    }
    
    /**
     * 库位删除
     * @time 2022/01/17 13:52
     * @param $id
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request) : Response
    {
         $id = $request->post('id');
         $ids = explode(',',$this->warehouseConfigModel->get_all_child_cate($id));
         $ids[] = $id;

         //判断是否有库存，如果有库存不给删除
        //------------//
         return CatchResponse::success($this->warehouseConfigModel->deleteBy($ids));
    }

    /**
     * 无权限库位列表
     * @time 2019年12月11日
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function getWarehouseConfig(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::success($this->warehouseConfigModel->getList($user['tenant_id']));
    }
    /**
     * 无权限库位列表
     * @time 2019年12月11日
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function loacalConfig(CatchAuth $auth,Request $request){
        $params = $request->post();
        $user = $auth->user();
        if($params['level']==1){
            $where = [];
            $where[] = ['deleted_at','=',0];
            $where[] = ['level','=',1];
            $data = Db::table('db_warehouse_config')->where($where)->select();
            return CatchResponse::success($data);
        }else if($params['level']==2){
            $parent_id = Db::table('db_warehouse_config')->where('config_id',$params['config_id'])->value('id');
            $where=[];
            $where[] = ['deleted_at','=',0];
            $where[]=['parent_id','=',$parent_id];
            $data=Db::table('db_warehouse_config')
                ->where($where)
                ->order('sort desc')
                ->select();
            return CatchResponse::success($data);
        }
    }

    public function location(CatchAuth $auth){

        $trayModel = new Tray;
        return CatchResponse::success($trayModel->getTrayList());
    }

    //库位托盘列表
    public function tray($config_id,CatchAuth $auth,Request $request){
        $user = $auth->user();

        $where = [];
        $where[]=['config_id','=',$config_id];
        $where[]=['status','in',[0,2]];

        $tray = (new Stock)->where($where)->column('tray_id');

        return CatchResponse::success(array_values(array_unique($tray)));
    }

    //查询某一个库位具体情况 货物数量
    public function getWarehouseConfigInfo($config_id,CatchAuth $auth,Request $request){
        $user = $auth->user();
        //$map[]=['deleted_at','=',0];
        $map[]=['status','in',[0,2]];
        $map[]=['config_id','=',$config_id];
        $map[]=['tenant_id','=',$user['tenant_id']];
        $list    = (new Stock)->field('sum(Good_Qty + Hold_Qty + NG_Qty) as stock')->where($map)->select()->toArray();
        $arr = array_column($list,'stock');
        $sum = array_sum($arr);

        return CatchResponse::success(['total'=>$sum]);
    }
}